<template>
  <div class="nav-home">
    <!-- 头部区域 -->
    <div class="nav-header">
      <div class="header-content">
        <div class="logo">
          <h1>导航首页</h1>
        </div>
        
        <!-- 搜索框 -->
        <div class="search-box">
          <el-select v-model="searchEngine" class="search-engine">
            <el-option 
              v-for="engine in searchEngines" 
              :key="engine.value"
              :label="engine.label"
              :value="engine.value"
            />
          </el-select>
          <el-input 
            v-model="searchKeyword"
            placeholder="搜索..." 
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>

        <div class="header-right">
          <template v-if="isLogin">
            <el-button type="primary" @click="toAdmin">后台管理</el-button>
            <el-button @click="handleLogout">退出</el-button>
          </template>
          <el-button v-else type="primary" @click="toLogin">登录</el-button>
        </div>
      </div>
    </div>

    <div class="main-container">
      <!-- 左侧分类目录 -->
      <div class="nav-sidebar">
        <div class="category-list">
          <div v-for="group in navGroups" 
               :key="group.id"
               class="category-item"
               :class="{ active: activeGroup === group.id }"
               @click="scrollToGroup(group.id)">
            <div class="category-icon" v-if="group.groupIcon" v-html="group.groupIcon">
            </div>
            <div class="category-icon" v-else>
              <el-icon><Folder /></el-icon>
            </div>
            <span class="category-name">{{ group.groupName }}</span>
          </div>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="nav-content" ref="contentRef">
        <el-empty v-if="loading" :description="'加载中...'" />
        
        <template v-else>
          <div v-for="group in navGroups" 
               :key="group.id" 
               class="nav-group"
               :id="`group-${group.id}`">
            <div class="group-header">
              <div class="group-icon" v-if="group.groupIcon" v-html="group.groupIcon"></div>
              <div class="group-icon" v-else>
                <el-icon><Folder /></el-icon>
              </div>
              <h2 class="group-title">{{ group.groupName }}</h2>
            </div>
            
            <div class="nav-links">
              <div v-for="link in group.links" 
                   :key="link.id"
                   class="link-card">
                <a :href="link.url"
                   target="_blank"
                   class="nav-link"
                   :title="link.linkDesc || link.name">
                  <div class="link-icon" v-if="link.icon" v-html="link.icon"></div>
                  <div class="link-icon" v-else>
                    <el-icon><Link /></el-icon>
                  </div>
                  <span class="link-name">{{ link.name }}</span>
                </a>
                <p class="link-desc" v-if="link.linkDesc">{{ link.linkDesc }}</p>
              </div>
            </div>
          </div>
        </template>

        <el-backtop target=".nav-content" :visibility-height="200" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { request } from '@/utils/request'
import { ElMessage } from 'element-plus'
import { Search, Folder, Link } from '@element-plus/icons-vue'

const router = useRouter()
const navGroups = ref([])
const isLogin = ref(false)
const activeGroup = ref(null)
const contentRef = ref(null)

// 搜索相关
const searchEngine = ref('baidu')
const searchKeyword = ref('')
const searchEngines = [
  { label: '百度一下', value: 'baidu', url: 'https://www.baidu.com/s?wd=' },
  { label: '搜狗搜索', value: 'sogou', url: 'https://www.sogou.com/web?query=' },
  { label: 'Bing必应', value: 'bing', url: 'https://cn.bing.com/search?q=' },
  { label: '哔哩哔哩', value: 'bilibili', url: 'https://search.bilibili.com/all?keyword=' },
  { label: '谷歌搜索', value: 'google', url: 'https://www.google.com/search?q=' }
]

const loading = ref(false)

// 处理搜索
const handleSearch = () => {
  if (!searchKeyword.value) return
  const engine = searchEngines.find(e => e.value === searchEngine.value)
  if (engine) {
    window.open(engine.url + encodeURIComponent(searchKeyword.value))
  }
}

// 获取导航数据
const getNavData = async () => {
  loading.value = true
  try {
    const res = await request('/api/nav/home')
    if (res.code === 200) {
      navGroups.value = res.data
    }
  } catch (error) {
    console.error('获取导航数据失败:', error)
    ElMessage.error('获取导航数据失败')
  } finally {
    loading.value = false
  }
}

// 检查登录状态
const checkLoginStatus = () => {
  const token = localStorage.getItem('token')
  isLogin.value = !!token
}

// 跳转到登录页
const toLogin = () => {
  router.push('/login')
}

// 跳转到后台
const toAdmin = () => {
  router.push('/dashboard')
}

// 退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  isLogin.value = false
  ElMessage.success('退出成功')
  getNavData()
}

// 滚动到指定分组
const scrollToGroup = (groupId) => {
  activeGroup.value = groupId
  const element = document.getElementById(`group-${groupId}`)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
}

// 防抖函数
const debounce = (fn, delay) => {
  let timer = null
  return function (...args) {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => fn.apply(this, args), delay)
  }
}

// 优化滚动监听
const handleScroll = debounce(() => {
  if (!contentRef.value) return
  const groups = contentRef.value.getElementsByClassName('nav-group')
  const scrollTop = contentRef.value.scrollTop
  
  for (let i = 0; i < groups.length; i++) {
    const rect = groups[i].getBoundingClientRect()
    if (rect.top >= 0 && rect.top <= window.innerHeight / 2) {
      activeGroup.value = navGroups.value[i].id
      break
    }
  }
}, 100)

onMounted(() => {
  checkLoginStatus()
  getNavData()
  contentRef.value?.addEventListener('scroll', handleScroll)
})

onBeforeUnmount(() => {
  contentRef.value?.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
.nav-home {
  min-height: 100vh;
  background: #f0f2f5;
}

.nav-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0,0,0,.1);
}

.header-content {
  max-width: 1400px;
  margin: 0 auto;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.logo h1 {
  font-size: 20px;
  margin: 0;
  color: #1a1a1a;
}

.search-box {
  flex: 1;
  max-width: 600px;
  display: flex;
  gap: 10px;
}

.search-engine {
  width: 120px;
}

.search-input {
  flex: 1;
}

.header-right {
  display: flex;
  gap: 10px;
}

.main-container {
  display: flex;
  margin-top: 70px;
  min-height: calc(100vh - 70px);
}

.nav-sidebar {
  position: fixed;
  left: 0;
  width: 220px;
  height: calc(100vh - 70px);
  background: #fff;
  padding: 20px 0;
  overflow-y: auto;
  border-right: 1px solid #eee;
}

.category-item {
  display: flex;
  align-items: center;
  padding: 12px 24px;
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 4px;
  margin: 0 10px;
}

.category-item:hover {
  background: #f0f2f5;
}

.category-item.active {
  background: #e6f4ff;
  color: #1890ff;
}

.category-icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  transition: all 0.3s;
}

.category-item.active .category-icon {
  color: #1890ff;
}

.category-icon :deep(svg) {
  width: 100%;
  height: 100%;
}

.nav-content {
  flex: 1;
  margin-left: 220px;
  padding: 20px 40px;
  overflow-y: auto;
}

.nav-group {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
}

.group-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.group-icon {
  width: 32px;
  height: 32px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f2f5;
  border-radius: 8px;
  color: #666;
  transition: all 0.3s;
}

.group-header:hover .group-icon {
  background: #e6f4ff;
  color: #1890ff;
}

.group-title {
  font-size: 20px;
  font-weight: 500;
  color: #1a1a1a;
  margin: 0;
}

.nav-links {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 16px;
}

.link-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s;
  border: 1px solid transparent;
}

.link-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,.1);
  border-color: #1890ff;
  background: #fff;
}

.link-card:hover .link-icon {
  background: #e6f4ff;
  color: #1890ff;
}

.nav-link {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: #1a1a1a;
}

.link-icon {
  width: 32px;
  height: 32px;
  margin-right: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
  border-radius: 8px;
  transition: all 0.3s;
  color: #666;
}

.link-icon :deep(svg) {
  width: 20px;
  height: 20px;
}

.link-name {
  font-size: 15px;
  font-weight: 500;
}

.link-desc {
  margin: 8px 0 0;
  font-size: 13px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

/* 响应式布局优化 */
@media screen and (max-width: 768px) {
  .nav-sidebar {
    display: none;
  }
  
  .nav-content {
    margin-left: 0;
    padding: 20px;
  }
  
  .nav-links {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  }
  
  .header-content {
    flex-direction: column;
    padding: 10px;
  }
  
  .search-box {
    width: 100%;
  }
}

/* 加载状态样式 */
.el-empty {
  margin: 100px auto;
}

/* 滚动条美化 */
.nav-content::-webkit-scrollbar {
  width: 6px;
}

.nav-content::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}

.nav-content::-webkit-scrollbar-track {
  background: #f5f5f5;
}

/* 链接卡片动画效果 */
.link-card {
  position: relative;
  overflow: hidden;
}

.link-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(120deg, transparent 30%, rgba(255, 255, 255, .6), transparent 70%);
  transform: translateX(-100%);
}

.link-card:hover::after {
  transition: transform 0.5s;
  transform: translateX(100%);
}
</style> 